package com.ruan.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruan.common.Code;
import com.ruan.common.R;
import com.ruan.common.Result;
import com.ruan.mapper.ParticipantMapper;
import com.ruan.pojo.Employee;
import com.ruan.pojo.Participant;
import com.ruan.service.EmployeeService;
import com.ruan.service.ParticipantService;
import com.ruan.service.ProjectService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/participant")
public class ParticipantController {
    @Autowired
    private ParticipantService participantService;
    @Autowired
    private ParticipantMapper participantMapper;
    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private ProjectService projectService;

    //新增项目参与员工的名单@RequestBody Participant participant
    @PostMapping("/saveParticipantAssignmentInfo")
    @Transactional
    public Result save(@RequestBody Map<String, Object> params){
//        System.out.println("participant的参数有"+params);
//        log.info("新增项目参与员工的名单，项目参与员工的名单信息：{}",projectId,employeeId);//participant.toString()

        Long projectId = Long.parseLong(params.get("projectId").toString());
//        System.out.println("projectId是"+projectId);
        if (projectId != null) {
            if (projectService.getById(projectId) == null) {
                //如果项目不存在，则返回错误信息
                return new Result(Code.SAVE_ERR,"项目不存在");
            }
        }

        //前端传来的参数employeeId是一个数组
        //前端：如果selectedEmployee是一个数组，那么将其赋值给employeeId，employeeId也会变成一个数组
        //this.projectAssignmentForm.employeeId = this.projectAssignmentForm.selectedEmployee

        //System.out.println("params: " + params);
//        List<String> employeeIdStrings = (List<String>)params.get("employeeId");//(List<Long>)

        Object employeeIdObj = params.get("employeeId");
        List<String> employeeIdStrings = null;

        if (employeeIdObj instanceof List) {
            // 当 employeeId 是 List 的时候
            employeeIdStrings = (List<String>) employeeIdObj;

        } else if (employeeIdObj instanceof String) {
            // 当 employeeId 是 String 的时候
            employeeIdStrings = Collections.singletonList((String) employeeIdObj);
        }

        List<Long> employeeIds = employeeIdStrings.stream()
                .map(Long::parseLong)
                .collect(Collectors.toList());

        for (int i = 0; i < employeeIds.size(); i++) {
            Long employeeId = employeeIds.get(i);
            Employee employee = employeeService.getById(employeeId);
            if (employee == null || employee.getStatus().equals("离职")) {
                // 如果 employee 离职了，则跳过当前循环
//                System.out.println("跳过离职员工：" + employeeId);
//                continue;
                // 如果有一个 employee 离职了，则需要重新选择
//                System.out.println("需要重新选择：" + employeeId);
                //想要回滚就要报个异常
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return new Result(Code.SAVE_ERR,"员工"+employee.getName()+"刚离职，请重新选择");
            }
            //System.out.println("看看遍历的参数"+employeeId);
            Participant participant = new Participant();
            participant.setProjectId(projectId);
            participant.setEmployeeId(employeeId);
            //查找participant表里的项目负责人，如果有了，就不再重复插入
            LambdaQueryWrapper<Participant> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Participant::getProjectId,projectId);
            queryWrapper.eq(Participant::getEmployeeId,employeeId);

            int count = participantMapper.selectCount(queryWrapper);
            //System.out.println("查找participant表里的项目负责人，如果有了，就不再重复插入:"+count);
            //防止重复插入
            if (count == 0) {
                //或者
                //if (count != 0) {
                //continue; // 跳过当前循环
                //}
                //System.out.println("负责人插入的是："+participant);
                participantService.save(participant);
            }
        }
//save方法继承自mybatis-plus的父接口IService（看看application.yml文件）,可以直接调用
        return new Result(Code.SAVE_OK,"新增项目参与员工名单成功");
    }
}
